import time
from datetime import datetime, timedelta

from flask import current_app
from sqlalchemy import or_
import jwt

from apps.models.user import User
from libs.tools import response


def authenticate(username, password):
    # 用户登录，登录成功返回token，写将登录时间写入数据库；登录失败返回失败原因

    user = User.query.filter(or_(User.email == username, User.mobile == username)).first()

    if user and user.is_delete == 0:
        if user.verify_password(password):
            user.login_time = time.time()
            user.token_expired = time.time() + current_app.config.get('TOKEN_EXP_HOURS') * 60 * 60
            user.save()
            token = encode_auth_token(user.id, user.login_time)
            data = {'token': token.decode()}
            return response(status_code=201, data=data, msg='登陆成功')
        return response(status_code=401, code=1, msg='验证密码错误')
    return response(status_code=401, code=1, msg='该用户不存在')


def encode_auth_token(user_id, login_time):
    # 生成认证Token

    try:
        payload = {
            'exp': datetime.utcnow() + timedelta(hours=current_app.config.get('TOKEN_EXP_HOURS')),
            'iat': datetime.utcnow(),
            'iss': 'ken',
            'data': {'id': user_id, 'login_time': login_time}
        }
        return jwt.encode(payload, current_app.config.get('SECRET_KEY'), algorithm="HS256")
    except Exception as e:
        return e


def decode_auth_token(auth_token):
    # 校验 token

    payload = jwt.decode(auth_token, current_app.config.get('SECRET_KEY'), options={'verify_exp': True})
    if ('data' in payload) and ('id' in payload['data']):
        return payload
    else:
        return response(status_code=401, code=1, msg='TOKEN 失效')
